package com.briup.store.service.impl;


import com.briup.common.exception.SystemException;
import com.briup.common.response.CodeAndMessageEnum;
import com.briup.common.utils.BeanCopyUtils;
import com.briup.common.utils.UserContext;
import com.briup.store.domain.dto.OrderInsertDTO;
import com.briup.store.domain.dto.OrderItemInsertDTO;
import com.briup.store.domain.pojo.Goods;
import com.briup.store.domain.vo.OderItemAndGoodsVO;
import com.briup.store.mapper.GoodsMapper;
import com.briup.store.mapper.OrderItemMapper;
import com.briup.store.mapper.OrderMapper;
import com.briup.store.mapper.ShopcarMapper;
import com.briup.store.domain.pojo.Order;
import com.briup.store.domain.pojo.OrderItem;
import com.briup.store.service.OrderService;
import com.briup.store.domain.vo.OrderGetDetailVO;
import com.briup.store.domain.vo.OrderQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

/**
* @author qinyc
* @description 针对表【es_order(订单表)】的数据库操作Service实现
* @createDate 2024-12-24 09:16:52
*/
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ShopcarMapper shopcarMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    @Transactional
    public String addOrder(OrderInsertDTO orderInsert) {
        /**
         * 1.参数校验
         */
        if (Objects.isNull(orderInsert)){
            throw new SystemException(CodeAndMessageEnum.ORDER_INFO_IS_NULL);
        }

        if (Objects.isNull(orderInsert.getOrderItemCreateDTOs()) || orderInsert.getOrderItemCreateDTOs().isEmpty()){
            throw new SystemException(CodeAndMessageEnum.ORDER_ITEM_INFO_IS_NULL);
        }

        /**
         * 判断收件人、收货地址、手机号、商品总价格都不能为空
         */
        if (!StringUtils.hasText(orderInsert.getReceiveUsername())){
            throw new SystemException(CodeAndMessageEnum.RECEIVE_USERNAME_IS_NULL);
        }

        /**
         * 2.插入数据库
         *  a.新增订单信息
         *  b.新增订单项信息
         */
        //2.1 新增订单信息
        //订单对象
        Order order = BeanCopyUtils.copyBean(orderInsert, Order.class);
        //获取订单ID（随机的UUID）
        String orderId = UUID.randomUUID().toString();

        order.setId(orderId);
        // TODO 当前用户默认为1
        order.setUserId(UserContext.getUser());
        order.setCreateDate(LocalDateTime.now());
        //状态1：已创建未支付
        order.setStatus(1);

        //order新增到数据库
        orderMapper.insert(order);

        /*
            2.2 新增订单项信息
         */
        //封装订单项实体
        List<OrderItemInsertDTO> orderItemCreateDTOs =
                orderInsert.getOrderItemCreateDTOs();

        //创建实体集合
        List<OrderItem> orderItems = new ArrayList<>();

        //遍历 订单项DTO 集合对象 ----> 订单项DTO
        for (OrderItemInsertDTO orderItemCreateDTO : orderItemCreateDTOs) {
            //创建订单项实体类型对象
            OrderItem orderItem = new OrderItem();
            //设置订单ID
            orderItem.setOrderId(orderId);
            //设置商品Id
            orderItem.setGoodsId(orderItemCreateDTO.getGoods());
            //设置商品数量
            orderItem.setNum(orderItemCreateDTO.getNum());
            //添加道歉集合
            orderItems.add(orderItem);
        }

        /**
         * 批量新增订单项信息
         *  insert into es_order_item (order_id,goods_id,num)
         *  values (#{orderId},#{goodsId},#{num}) ,
         *          (#{orderId},#{goodsId},#{num}),
         *          (#{orderId},#{goodsId},#{num}),
         *          (#{orderId},#{goodsId},#{num})
         *
         *  delete from es_user where id in (1,2,3)
         */
        orderItemMapper.batchInsert(orderItems);

        /**
         * 3.根据订单项id集合删除购物车中的商品信息
         */
        List<Integer> ids = orderInsert.getOrderItemCreateDTOs()
                .stream()
                .map(o -> o.getGoods())
                .collect(Collectors.toList());

//        List<Integer> list = new ArrayList<>();
//        for (OrderItemInsertDTO orderItemCreateDTO : orderInsert.getOrderItemCreateDTOs()) {
//            list.add(orderItemCreateDTO.getGoods());
//        }

        //删除订单相关购物车信息
        shopcarMapper.deleteByUserIdAndGoodsId(UserContext.getUser(),ids);

        //4.扣减商品库存数量
        for (OrderItemInsertDTO item : orderItemCreateDTOs) {
            Goods goods = goodsMapper.getGoodsById(item.getGoods());
            //计算最新库存
            int storeNum = goods.getStoreNum() - item.getNum();
            if(storeNum < 0) {
                throw new SystemException(CodeAndMessageEnum.GOODSTOCK_IS_NOT_ENOUGH);
            }
            //修改库存
            goods.setStoreNum(storeNum);

            //更新商品库存信息
            goodsMapper.updateGood(goods);
        }

        return orderId;
    }

    @Override
    public List<OrderQueryVO> queryOrder() {
        List<Order> orders = orderMapper.selectOrdersByUserId(UserContext.getUser());
        return BeanCopyUtils.copyBeanList(orders,OrderQueryVO.class);
    }

    @Override
    public void closeOrder(String id) {
        //1.参数校验
        if (!StringUtils.hasText(id)){
            throw new SystemException(CodeAndMessageEnum.ORDER_ID_IS_NULL);
        }

        /**
         * 2.关闭订单(修改状态为5：已关闭)，注意只能关闭未支付的订单
         */
        //根据订单ID查询订单信息
        Order order = orderMapper.selectOrderById(id);

        if (order.getStatus() != 1){
            throw new SystemException(CodeAndMessageEnum.ORDER_HAS_BEEN_PAID);
        }

        //关闭订单
        orderMapper.updateStatus(id);

        //3.恢复商品库存
        // 根据订单id查询订单项信息(含商品id、num)
        List<OrderItemInsertDTO> orderItems =
                orderItemMapper.getOrderItemsByOrderId(id);
        //orderMapper.detailOrder(id).getOrderItems();

        //增加库存
        for(int i = 0; i < orderItems.size(); i++) {
            OrderItemInsertDTO o = orderItems.get(i);
            o.setNum(o.getNum() * -1);
            orderItems.set(i, o);
        }

        for (OrderItemInsertDTO item : orderItems) {
            Goods goods = goodsMapper.getGoodsById(item.getGoods());
            //计算最新库存
            int storeNum = goods.getStoreNum() - item.getNum();
            if(storeNum < 0) {
                throw new SystemException(CodeAndMessageEnum.GOODSTOCK_IS_NOT_ENOUGH);
            }
            //修改库存
            goods.setStoreNum(storeNum);

            //更新商品库存信息
            goodsMapper.updateGood(goods);
        }
    }

    @Override
    public OrderGetDetailVO detailOrder(String orderId) {
        //获取订单详情（含订单项）
        OrderGetDetailVO order = orderMapper.getDetailOrderWithoutGoods(orderId);

        //获取订单项信息，并补全商品信息
        List<OderItemAndGoodsVO> orderItems = order.getOrderItems();
        for (OderItemAndGoodsVO orderItem : orderItems) {
            //根据商品id查询商品信息
            Goods goods = goodsMapper.getGoodsById(orderItem.getId());
            orderItem.setName(goods.getName());
            orderItem.setCover(goods.getCover());
            orderItem.setPrice(goods.getPrice());
        }

        return order;
        //return orderMapper.detailOrder(orderId);
    }

    @Override
    public void updateOrderById(Order order) {
        /**
         * 参数校验
         */
        orderMapper.update(order);
    }

    @Override
    public List<OrderItemInsertDTO> getOrderItemByOrderId(String orderId) {
        List<OrderItemInsertDTO> list = orderItemMapper.getOrderItemsByOrderId(orderId);
        return list;
    }
}
